var currentNav = "main_nav_id_1";
var chatActivated = new Boolean(0);

require([ "dojo", "dojo/_base/xhr", "dojo/on", "dojo/dom", "dojo/dom-class", "dojo/parser",
		"dojo/query", "dojo/dom-attr", "dojo/dom-style", "dojo/dom-construct", "dojo/keys",
		"dojox/widget/Standby", "dojo/fx/Toggler", "dojo/fx", "dojox/fx/text", "dojox/html", "dojox/validate", "dojo/_base/connect", 
		"dijit/registry", "dojo/_base/array", "dojo/_base/lang",
		"dojox/html/_base", "dijit/DropDownMenu", "dijit/MenuSeparator", "dijit/MenuBarItem", "dijit/PopupMenuItem",
		"dijit/MenuBar", "dijit/PopupMenuBarItem", "dijit/form/ToggleButton",
		"dijit/form/ComboButton", "dijit/Menu", "dijit/MenuItem", "dijit/form/DropDownButton",
		"dijit/TooltipDialog", "dojo/NodeList-traverse", "dojo/NodeList-manipulate",
		"dojo/io/script", "dojox/cometd", "dojox/cometd/callbackPollTransport",
		"dojox/validate/us", "dojox/validate/web", "dijit/form/CheckBox", "dijit/form/Textarea",
		"dijit/form/Select", "dijit/form/TextBox", "dijit/form/ValidationTextBox",
		"dijit/form/DateTextBox", "dijit/form/TimeTextBox", "dijit/form/Button",
		"dijit/form/RadioButton", "dijit/form/Form", "dijit/form/DateTextBox",
		"dojox/form/BusyButton", "dojox/form/CheckedMultiSelect", "dojo/domReady!" ],
		function(dojo, xhr, on, dom, domClass, parser, query, domAttr, domStyle, construct, keys,
				Standby, Toggler, fx, text, html, validate, connect, registry, array, lang) {
			var standby = new Standby({
				target : "contentpane"
			});
			parser.parse();
			showOverlay = function(target) {
				console.log("show overlay called for : " + target);
				require([ "dojox/widget/Standby", "dijit/form/Button", "dojo/domReady!" ],
						function(Standby, Button) {
							standby = new Standby({
								target : target
							});
							document.body.appendChild(standby.domNode);
							standby.show();
						});
			}

			hideOverlay = function(target) {
				console.log("hide overlay called for : " + target);
				require([ "dojox/widget/Standby", "dijit/form/Button", "dojo/domReady!" ],
						function(Standby, Button) {
							standby = new Standby({
								target : target
							});
							document.body.appendChild(standby.domNode);
							standby.hide();
						});
			}

			clickmenu = function(target) {

				var submenu = domAttr.get(target, "subnav-class");
				var menuId = domAttr.get(target, "id");

				var t = new Toggler({
					node : submenu,
					showDuration : 500,
					hideDuration : 500,
					showFunc : fx.wipeIn,
					hideFunc : fx.wipeOut
				});
				var t2 = new Toggler({
					node : currentNav,
					showDuration : 500,
					hideDuration : 500,
					showFunc : fx.wipeIn,
					hideFunc : fx.wipeOut
				});
				if (currentNav != submenu) {
					query("#menubar div").removeClass("menu_selected");
					domClass.add(menuId, "menu_selected");
					t2.hide();
					t.show();
					currentNav = submenu;
				}
				var submenutarget = query(dojo.byId(submenu)).query("div:first-child")[0];
				console.log("handling onclick event" + submenutarget);
				clickSubmenu(submenutarget);
				loadContentPane(submenutarget);
				paramUrl = domAttr.get(submenutarget, "content-url");
				if (paramUrl && paramUrl.indexOf("showQuestionnaire") != -1) {
					console.log("show questionnaire page"); 
					contenturl = "/profile/questionnaire.htm";
					loadContentPanewithUrl("/profile/questionnaire.htm"); 
				}
			}

			clickSubmenu = function(target) {

				console.log(" handling clickSubmenu using " + target);
				query(".submenu_item").removeClass("menu_selected");
				domClass.add(target, "menu_selected");
				imagepaneurl = domAttr.get(target, "img-url");

				/*require([ "dojo/_base/fx" ], function(fx) {
					fx.animateProperty({
						node : "submenublock",
						duration : 1000,
						properties : {
							height : 100
						}
					}).play();
				});*/
				dom.byId("header_image_block").innerHTML = "";

			}

			loadContentPaneCallback = function(newContent, ioargs) {
				var xhrstatus = ioargs.xhr.status;
				console.log(" xhr status : " + xhrstatus);
				html.set(dojo.byId("contentpane"), newContent, {
			        executeScripts: true,
			        scriptHasHooks: false,
			        renderStyles: true
			    });
				if (contenturl.indexOf("userChat.htm") != -1) {
					parser.parse("chatting_pane");
					initializeChat();
					handleChatSubmit();
					document.body.appendChild(standby.domNode);
					standby.hide();
				} else if (contenturl.indexOf("showUsers.htm") != -1) {
					if (newContent.indexOf("loginPageResponse") != -1) {
						parser.parse("login_content_td");
						handleLoginSubmit();
						loadUserRegistrationpage();
					} else {
						parser.parse("users_container");
						query(".user_chat").on("click", function(e) {
							startChatWindow(e.currentTarget);
							// loadContentPane(e.currentTarget); TODO vinod.neelam | user not taken to a new page.
						});
					}
					document.body.appendChild(standby.domNode);
					standby.hide();
				} else if(contenturl.indexOf("login.htm") != -1) {
					parser.parse("login_content_td"); 
					handleLoginSubmit();
					loadUserRegistrationpage();				
				} else if(contenturl.indexOf("updateQuestions.htm") != -1){
					parser.parse("contentpane"); 
					handleAddQRow();
					handleUpdateQSubmit();					
					document.body.appendChild(standby.domNode);
					standby.hide();
				} else if(contenturl.indexOf("questionnaire.htm") != -1){
					console.log("questionnaire form display"); 
					parser.parse("contentpane"); 
					handleQuestionnaireFormSubmit();
					document.body.appendChild(standby.domNode);
					standby.hide();
				}else {
					document.body.appendChild(standby.domNode);
					standby.hide();
				}
				
			}
			
			
			handleQuestionnaireFormSubmit = function() {
				var qform = dojo.byId("questionnaireForm");
				console.log("questionnaire form handle submit"); 
				dojo.connect(qform, "onsubmit", function(e) {
					console.log("q form submitted"); 
					document.body.appendChild(standby.domNode);
					standby.show();
					var xhrArgs = {
						form : dojo.byId("questionnaireForm"),
						url: '/profile/questionnaireSubmit.htm',
						load : function(data) {
							if(data.indexOf("success") != -1){
								window.location.reload();
							} else {
								console.log("error : " + data);
							}
							
						},
						error : function(error) {
							console.log("error : " + error);
							dojo.byId("contentpane").innerHTML = "";
							document.body.appendChild(standby.domNode);
							standby.hide();
						}
					}
										
					if(registry.byId("questionnaireForm").validate()){ 
						console.log("q form validated"); 
						xhr.post(xhrArgs);		
					} else {
						console.log("q form validation failed");
						document.body.appendChild(standby.domNode);
						standby.hide();
					}
							
				});
			}
			
			handleAddQRow = function(){
				query("#addQuestion").on("click", function(e) {
						console.log("handle add row"); 
					cloneTarget = dojo.byId("temp_clone");
					currentCount = domAttr.get(cloneTarget, "qCount");
					var newQRow = lang.clone(query("#temp_clone").query("tr")[0]);
					domAttr.set(newQRow, "id", "qcount" + currentCount);
					construct.place(newQRow, dojo.byId("qButtonRow"), "before");
						console.log(query("#qcount" + currentCount).query("input")[0]);
					domAttr.set(query("#qcount" + currentCount).query("textarea")[0], "name", "questions[" + currentCount + "].questionDesc");
					domAttr.set(query("#qcount" + currentCount).query("textarea")[0], "data-dojo-type", "dijit.form.Textarea");
					parser.parse("qcount" + currentCount);
					currentCount++;
					domAttr.set(cloneTarget, "qCount", currentCount);
					
				});
			}
			
			activateChat = function(target){
				contenturl = domAttr.get(target, "content-url");
				document.body.appendChild(standby.domNode);
				standby.show();
				xhr.get({
					url : contenturl,
					load : activateChatCallBack,
					error : function() {
						document.body.appendChild(standby.domNode);
						standby.hide();
					}
				});
			}
			
			activateChatCallBack = function(token){
				initialize(token);
				domStyle.set("activateChat", "display", "none");
				document.body.appendChild(standby.domNode);
				standby.hide();
				setInterval("heartBeat()", 30000);
				chatActivated = true;
			}
			
			
			startChatWindow = function(target){
				if(chatActivated == false){
					console.log("chat not activated ... ");
					
					return;
				}
				contenturl = domAttr.get(target, "window-data-url");
				console.log(" handling startChatWindow using " + target + " and context url "
						+ contenturl);
				document.body.appendChild(standby.domNode);
				standby.show();
				xhr.get({
					url : contenturl,
					handleAs:"json",
					load : startChatWindowCallback,
					error : function() {
						document.body.appendChild(standby.domNode);
						standby.hide();
					}
				});
			}
			
			var currentLeft = 0;
			var openChats = []; 
			
			startChatWindowCallback = function(newContent, ioargs){
				lang.mixin(newContent, {
					handlepos: {
				        l: 0,
				        t: 0
				    },
				    currentLeft: currentLeft});
				
				var userMatched = new Boolean(0);
				array.forEach(openChats, function(item, i){
					if(item.indexOf(newContent.toUser) != -1){
						userMatched = true;
						return;
					}
				});
				
				if(userMatched == false){
					createChatWindow(newContent);				
					currentLeft += 260;
					openChats.push(newContent.toUser);
					handleChatWindowSubmit(newContent.formId, newContent.inputTextId, newContent.inputId + "history");
				}				
				
				document.body.appendChild(standby.domNode);
				standby.hide();
			}
			
			handleLoginSubmit = function(){
				var loginForm = dojo.byId("loginForm");
				dojo.connect(loginForm,"onsubmit", function(e) {
					document.body.appendChild(standby.domNode);
					standby.show();
					var xhrArgs = {
						form : dojo.byId("loginForm"),
						url: '/j_spring_security_check',
						load : function(data) {
							if (data.indexOf("loginPageResponse") != -1) {
								destroyWidgets();
								html.set(dojo.byId("contentpane"), data, {
							        executeScripts: true,
							        scriptHasHooks: false,
							        renderStyles: true
							    });								
								parser.parse("login_content_td"); 
								handleLoginSubmit();
								loadUserRegistrationpage();	
							}else {
								window.location.reload();
							}
						},
						error : function(error) {
							dojo.byId("contentpane").innerHTML = "error occurred";
							destroyWidgets();
							document.body.appendChild(standby.domNode);
							standby.hide();
						}
					}
					
					if(registry.byId("loginForm").validate()){ 
						xhr.post(xhrArgs);
					} else {
						document.body.appendChild(standby.domNode);
						standby.hide();
					}
				});
			}

			loadContentPane = function(target) {
				contenturl = domAttr.get(target, "content-url");
				console.log(" handling loadContentPane using " + target + " and context url "
						+ contenturl);
				if (contenturl) {
					destroyWidgets();
					document.body.appendChild(standby.domNode);
					standby.show();
					xhr.get({
						url : contenturl,
						load : loadContentPaneCallback,
						error : function() {
							dom.byId("contentpane").innerHTML = "";
							document.body.appendChild(standby.domNode);
							standby.hide();
						}
					});
				} else {
					dom.byId("contentpane").innerHTML = "";
				}
			}
			
			loadContentPanewithUrl = function(contenturl) {
				console.log(" handling loadContentPane with context url "
						+ contenturl);
				if (contenturl) {
					destroyWidgets();
					document.body.appendChild(standby.domNode);
					standby.show();
					xhr.get({
						url : contenturl,
						load : loadContentPaneCallback,
						error : function() {
							dom.byId("contentpane").innerHTML = "";
							document.body.appendChild(standby.domNode);
							standby.hide();
						}
					});
				} else {
					dom.byId("contentpane").innerHTML = "";
				}
			}

			submitEvent = function() {
				query(".disable_user").on("click", function(e) {
					document.body.appendChild(standby.domNode);
					standby.show();
					contenturl = domAttr.get(e.target, "endpoint");
					userid = domAttr.get(e.target, "userid");
					value = e.target.checked;
					console.log("value checked : " + value);
					var xhrArgs = {
						url : contenturl,
						content : {
							user_id : userid,
							status : value
						},
						load : function(data) {
							document.body.appendChild(standby.domNode);
							standby.hide();
							if (data.indexOf("success")) {
								console.log("successfully changed status of user ");
							}
						},
						error : function(error) {
							document.body.appendChild(standby.domNode);
							standby.hide();
						}
					}
					xhr.get(xhrArgs);
				});
			}

			destroyWidgets = function() {
				array.forEach(registry.toArray(), function(widget, i) {
					// console.log(widget.declaredClass);
					if (widget.declaredClass != 'dojox.widget.Standby' && widget.declaredClass != 'dijit._MasterTooltip') { 
						widget.destroy();
					}
				});
				// console.log(registry.length);
			}
			clickmenu(dom.byId("main_nav_1"));
			query(".menu_item").on("click", function(e) {
				clickmenu(e.currentTarget);
			});
			
			

			query(".submenu_item").on("click", function(e) {
				clickSubmenu(e.currentTarget);
				loadContentPane(e.currentTarget);
			});

			query("#login_url").on("click", function(e) {
				clickSubmenu(e.currentTarget);
				loadContentPane(e.currentTarget);
				domClass.remove(e.currentTarget, "menu_selected");
				query("#lastRequest").innerHTML('true');
			});
			
			query('#activateChat').on("click",function(e){
				activateChat(e.currentTarget);
			});

			query("#registry_length").on("click", function(e) {
				require([ "dijit/registry", "dojo/_base/array" ], function(registry, array) {
					array.forEach(registry.toArray(), function(widget, i) {
						console.log(widget.declaredClass);
						//widget.destroy();
					});
					console.log(registry.length);
				});
			});

			handleChatSubmit = function() {
				var xhrArgs = {
					url : "/chat/sendChat.htm",
					form : dojo.byId("chat_text_form"),
					load : function(data) {
						dojo.byId("input_chat").innerHTML += (data + "<br/>");
					},
					error : function(error) {
						dojo.byId("input_chat").innerHTML = "";
					}
				}
				submitChat = function(e) {
					console.log(" - send chat handler - called and submitting chat !!");
					xhr.post(xhrArgs);
					return false;
				}
				keyPressHandler = function(e) {
					if (e.type == 'keypress' && e.charOrCode != keys.ENTER) {
						return false;
					}
					if(dojo.isIE){
						//xhr.post(xhrArgs);
					}
					console.log(" key press handler called !!");
				}
				dojo.connect(dojo.byId("send_chat"), "onclick", submitChat);
				dojo.connect(dojo.byId("chat_text_input"), "onkeypress", keyPressHandler);
			}
			
			handleChatWindowSubmit = function(formId, inputTextId, inputHistoryId) {
				var xhrArgs = {
					url : "/chat/sendChat5.htm",
					form : dojo.byId(formId),
					load : function(data) {
						dojo.byId(formId).text.value = "";
						dojo.byId(inputHistoryId).innerHTML += (data + "<BR/>");
					},
					error : function(error) {
						
					}
				}
				
				keyPressHandler = function(e) {
					if (e.type == 'keypress' && e.charOrCode == keys.ENTER && e.shiftKey ) {
						return false;
					} else if(e.type == 'keypress' && e.charOrCode == keys.ENTER){
						e.preventDefault();
						xhr.post(xhrArgs);
						return false;
					}
					if(dojo.isIE){
						//xhr.post(xhrArgs);
					}
				}

				dojo.connect(dojo.byId(inputTextId), "onkeypress", keyPressHandler);
			}

			handleUserRegistrationSubmit = function() {
				var regForm = dojo.byId("registerForm"); 
				dojo.connect(regForm,"onsubmit", function(e) {
					document.body.appendChild(standby.domNode);
					standby.show();
					var xhrArgs = {
						form : dojo.byId("registerForm"),
						url: '/public/registerUser.htm',
						load : function(data) {
							//dojo.byId("registrationPane").innerHTML = data;
							document.body.appendChild(standby.domNode);
							standby.hide();
							console.log("xhrget response data: " + data);
							if (data == 'success') {
								console.log(" reloading page for consistency.. ");
								window.location.reload();
							} else {
								domStyle.set("regFormMessage", "display", "inline");
								dojo.byId("regFormMessage").innerHTML = data;
							}
						},
						error : function(error) {
							dojo.byId("contentpane").innerHTML = "";
							document.body.appendChild(standby.domNode);
							standby.hide();
						}
					}
										
					if(registry.byId("registerForm").validate()){ 
						xhr.post(xhrArgs);		
					} else {
						document.body.appendChild(standby.domNode);
						standby.hide();
					}
							
				});
			}
			
			
			handleUpdateQSubmit = function() {
				var qform = dojo.byId("addQSubmitButton");
				console.log("q log : " + qform);
				dojo.connect(qform, "onclick", function(e) {
					console.log("q form submitted"); 
					document.body.appendChild(standby.domNode);
					standby.show();
					var xhrArgs = {
						form : dojo.byId("updateQ"),
						url: '/admin/updateQuestionsSubmit.htm',
						load : function(data) {
							if(data.indexOf("success") != -1){
								dojo.byId("responseMessage").innerHTML = "Successfully updated Questions.";
							}
							document.body.appendChild(standby.domNode);
							standby.hide();
							
						},
						error : function(error) {
							console.log("error : " + error);
							dojo.byId("contentpane").innerHTML = "";
							document.body.appendChild(standby.domNode);
							standby.hide();
						}
					}
										
					if(registry.byId("updateQ").validate()){ 
						console.log("q form validated"); 
						xhr.post(xhrArgs);		
					} else {
						console.log("q form validation failed");
						document.body.appendChild(standby.domNode);
						standby.hide();
					}
							
				});
			}
			
			

			

			loadUserRegistrationpageCallback = function(newContent, ioargs) {
				html.set(dojo.byId("registrationPane"), newContent, {
			        executeScripts: true,
			        scriptHasHooks: false,
			        renderStyles: true
			    });
				parser.parse("registrationPane"); 
				document.body.appendChild(standby.domNode);
				standby.hide();
				handleUserRegistrationSubmit();
			}

			loadUserRegistrationpage = function() {
				xhr.get({
					url : '/public/showRegistrationForm.htm',
					load : loadUserRegistrationpageCallback,
					error : function(ioargs) {
						dom.byId("contentpane").innerHTML = "error occured";
					}
				});
			}
			
			googlePopup = function() {
				var popupURL = "/public/login.htm?source=google";
				window.open(popupURL,
								"Popup",
								"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=630,height=450");
			}	
			
			linkedinPopup = function() {
				var popupURL = "/public/login.htm?source=linkedin";
				window.open(popupURL,
								"Popup",
								"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=630,height=450");
			}	
			
		    
		    heartBeat = function(){
		    	var xhrArgs = {
						url: '/chat/heartBeat.htm',
						handleAs: 'json',
						load : function(data) {
							console.log("xhrget response data: " + data);
							updateChatUserList(data);
						},
						error : function(error) {
							console.log("error occurred");
						}
					}
		    	xhr.get(xhrArgs);		
		    }
		    
		    updateChatUserList = function(data){
		    	console.log("updating chat user list.. size: " + data.onlineUsers.length);
		    }
		    
		    if(sessionToken){
		    	activateChatCallBack(sessionToken);
		    }
			
		});
